/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2022-01-01 18:12:17
 */

import { unref } from "vue";
import Palette from "@/utils/getImgColor";
import { imgColorType } from "./types";

// dom相关操作
export const useDom = () => {
  // 获取元素的translateX的值
  const getTranslateX = (el: HTMLElement): number => {
    return Number(
      getComputedStyle(unref(el), null)
        .getPropertyValue("transform")
        .split(",")[4]
    );
  };

  // 设置音频的播放位置
  const setAudioCurrent = (el: HTMLAudioElement, target: number) => {
    unref(el).currentTime = target;
  };

  let animateId: number | undefined; //动画id
  // 设置盒子内部的Y轴滚动位置
  const setScrollTop = (el: HTMLElement, targetTop: number) => {
    el = unref(el);
    const max = el.scrollHeight - el.getClientRects()[0]?.height || 0;
    if (targetTop > max) targetTop = max;
    cancelAnimationFrame(animateId as number);
    if (animateId !== undefined) {
      cancelAnimationFrame(animateId);
      animateId = undefined;
    }
    // 动画函数
    const animateFun = (el: HTMLElement, targetTop: number) => {
      const step = Math.ceil(Math.abs(el.scrollTop - targetTop) / 10);
      const targetArr = [targetTop - step, targetTop, targetTop + step];
      if (targetArr.includes(Math.ceil(el.scrollTop)) || targetTop > max)
        return cancelAnimationFrame(animateId as number);
      el.scrollTop > targetTop
        ? (el.scrollTop -= step)
        : (el.scrollTop += step);
      animateId = requestAnimationFrame(() => animateFun(el, targetTop));
    };
    animateFun(el, targetTop);
  };

  // 获取图片内的颜色
  const getImgColor = (imgUrl: string): Promise<string[]> => {
    let image = new Image();
    image.src = imgUrl;
    image.setAttribute("crossOrigin", "anonymous");
    return new Promise((resolve, reject) => {
      try {
        image.onload = function () {
          let palette = new Palette(image);
          const res = [palette.getVibrantColor(),palette.getLightVibrantColor(),palette.getDarkVibrantColor(),
            palette.getMutedColor(),palette.getLightMutedColor(),palette.getDarkMutedColor(),]
          resolve(res);
        };
      } catch (error) {
        reject(error)
      }
    });
  };

  return {
    getTranslateX,
    setAudioCurrent,
    setScrollTop,
    getImgColor
  };
};
